import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Activity from '../views/Activity.vue'
import Create from '../views/Create.vue'
import Auth from '../views/Auth.vue'
import Setting from '../views/Setting.vue'
import User from '../views/User.vue'
import NotFound from '../views/404.vue'
import Search from '../views/Search.vue'
import Edit from '../views/Edit.vue'

//=================辅助函数=================//

// 守卫需要登录的路由
function guardMyroute(to, from, next) {
  var isAuthenticated = false;
  let token = null
  if (localStorage.token) {
    token = localStorage.token
  }
  if (token)
    isAuthenticated = true;
  else
    isAuthenticated = false;
  if (isAuthenticated) {
    next(); // allow to enter route
  } else {
    next('/auth'); // go to '/auth';
  }
}

// 守卫登录后不能访问的路由
function redirectAfterLogin(to, from, next) {
  var isAuthenticated = false;
  let token = null
  if (localStorage.token) {
    token = localStorage.token
  }
  if (token)
    isAuthenticated = true;
  else
    isAuthenticated = false;
  if (!isAuthenticated) {
    next(); // allow to enter route
  } else {
    next('/'); // go to '/';
  }
}

//=================路由配置=================//
Vue.use(VueRouter)

// 路由配置
const routes = [{
  // 首页
  path: '/',
  name: 'Home',
  component: Home,
}, {
  // 首页
  path: '/search',
  name: 'Search',
  component: Search,
  props: true
}, {
  // 活动详情页
  path: '/activities/:id',
  name: 'Activity',
  component: Activity
}, {
  // 创建活动页
  path: '/create',
  name: 'Create',
  component: Create,
  beforeEnter: guardMyroute
}, {
  // 编辑活动页
  path: '/activities/:id/edit',
  name: 'Edit',
  component: Edit,
  beforeEnter: guardMyroute
}, {
  // 登录和注册页面
  path: '/auth',
  name: 'Auth',
  component: Auth,
  beforeEnter: redirectAfterLogin
}, {
  // 用户信息页
  path: '/users/:username',
  name: 'User',
  component: User
}, {
  // 设置页面
  path: '/setting',
  name: 'Setting',
  component: Setting,
  beforeEnter: guardMyroute
}, {
  // 404页
  path: '/404',
  name: 'NotFound',
  component: NotFound
}, {
  path: '*',
  redirect: "NotFound"
}]

// 创建路由器
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router